package net.begincode.maiev.monitor.bean;

import net.begincode.maiev.bean.MonitorConvertBean;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 抓取数据汇总容器
 * Created by Stay on 2017/5/25  19:25.
 */
public class CollectContainer {

    private ConcurrentHashMap<String, MonitorConvertBean> collectMap = new ConcurrentHashMap<>();

    private static enum Singleton {
        INSTANCE;
        private CollectContainer singleton;

        private Singleton() {
            singleton = new CollectContainer();
        }

        public CollectContainer getInstance() {
            return singleton;
        }
    }

    public static CollectContainer getInstance() {
        return Singleton.INSTANCE.getInstance();
    }


    /**
     * 记录未处理的数据
     *
     * @param completeName
     * @param requestTime
     * @param requestType
     * @param host
     * @param requestCount
     * @param projectId
     */
    public void recordMonitorData(String completeName, Long requestTime, String requestType, String host, Integer requestCount, Integer projectId, Long requestMaxTime, Date date) {
        MonitorConvertBean convertBean = collectMap.get(completeName);
        if (convertBean == null) {
            convertBean = new MonitorConvertBean(new AtomicInteger(requestCount), new AtomicLong(requestTime), new AtomicLong(requestMaxTime), host, requestType, projectId, date);
            MonitorConvertBean originalBean = collectMap.putIfAbsent(completeName, convertBean);
            if (originalBean != null) {
                convertBean = originalBean;
            }
        }
        convertBean.updateBean(requestTime, requestCount, requestMaxTime);
    }

    public void getDataMap(Map<String, MonitorConvertBean> map) {
        String countKey = null;
        for (Map.Entry<String, MonitorConvertBean> entry : collectMap.entrySet()) {
            countKey = entry.getKey();
            map.put(countKey, getAndRemove(countKey, entry.getValue()));
        }
    }

    public Map<String, MonitorConvertBean> getDataMap() {
        HashMap<String, MonitorConvertBean> map = new HashMap<>();
        for (Map.Entry<String, MonitorConvertBean> entry : collectMap.entrySet()) {
            map.put(entry.getKey(), entry.getValue());
        }
        return map;
    }

    /**
     * 根据k v 移除map中对应的数据 并返回移除前的value
     *
     * @param key
     * @param value
     * @return
     */
    private MonitorConvertBean getAndRemove(String key, MonitorConvertBean value) {
        while (!collectMap.remove(key, value)) {
            value = collectMap.get(key);
        }
        return value;
    }


}
